//
//   .h
//  UnionMedApp
//
//  Created by 唐家钦 on 16/2/25.
//  Copyright © 2016年 唐家钦. All rights reserved.
//

#import "TYCarouselView.h"

@interface TYCarouselView()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource>
@property (assign, nonatomic) NSUInteger interval;
@property (strong, nonatomic) UIImage *placeHolder;
@property (strong, nonatomic) NSTimer *timer;

@property (assign, nonatomic) NSInteger timeIndex;

@property (strong, nonatomic) UICollectionView * collectView;
@end

@implementation TYCarouselView
- (instancetype)init {
    self = [super init];
    if (self) {
        self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    [self reloadData];
}
#pragma mark ---NSTimer
- (void)setTimeInterval:(NSTimeInterval)timeInterval {
    _timeInterval = timeInterval;
    [self setUpTimer];
}

- (void)setUpTimer {
    if (self.timeInterval > 0 && self.hiddenTimer == NO && [self.delegate numberOfItemsForCarouselView:self] > 1) {
        if (!_timer) {
            self.timeIndex = 0;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:self.timeInterval target:self selector:@selector(updateWheel) userInfo:nil repeats:YES];
            [[NSRunLoop mainRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
            [self.timer fire];
        }
    }else {
        if (_timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
    }
}

- (void)updateWheel{
    self.timeIndex ++;
    if (self.timeIndex <= 1) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        int page = weakSelf.collectView.contentOffset.x / (weakSelf.collectView.frame.size.width - 1);
        if (weakSelf.scrollDirection == UICollectionViewScrollDirectionVertical) {
            page = weakSelf.collectView.contentOffset.y / (weakSelf.collectView.frame.size.height - 1);
        }
        if (page > 1) {
            page = 1;
        }
        
        if (weakSelf.scrollDirection == UICollectionViewScrollDirectionVertical) {
            [weakSelf.collectView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:page + 1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionCenteredVertically) animated:YES];
        }else {
            [weakSelf.collectView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:page + 1 inSection:0] atScrollPosition:(UICollectionViewScrollPositionCenteredHorizontally) animated:YES];
        }
//        [weakSelf.collectView setContentOffset:offset animated:YES];
//        [UIView animateWithDuration:0.5 animations:^{
//            weakSelf.collectView.contentOffset = offset;
//        }completion:^(BOOL finished) {
//            [weakSelf scrollViewDidEndScrollingAnimation:weakSelf.collectView];
//        }];
    });
}

- (void)dealloc {
    if (_timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

#pragma mark ---TYPageControl
- (TYPageControl *)pageControl {
    if (!_pageControl) {
        __weak typeof(self) weakSelf = self;
        _pageControl = [[TYPageControl alloc]init];
        [self addSubview:_pageControl];
        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(weakSelf);
            make.height.mas_equalTo(weakSelf).multipliedBy(0.27);
        }];
    }
    return _pageControl;
}



#pragma mark ---UICollectionView
- (UICollectionView *)collectView {
    if (!_collectView) {
        __weak typeof(self) weakSelf = self;
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.scrollDirection = self.scrollDirection;
        _collectView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) collectionViewLayout:flowLayout];
        _collectView.delegate = self;
        _collectView.dataSource = self;
        _collectView.backgroundColor = [UIColor clearColor];
        _collectView.showsVerticalScrollIndicator = NO;
        _collectView.showsHorizontalScrollIndicator = NO;
        _collectView.pagingEnabled = YES;
        _collectView.layer.masksToBounds = YES;
        [_collectView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"UICollectionViewCell"];
        [self addSubview:_collectView];
        [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(weakSelf);
            make.left.mas_equalTo(weakSelf);
            make.right.mas_equalTo(weakSelf);
            make.bottom.mas_equalTo(weakSelf);
        }];
        self.currentIndex = _currentIndex;
    }
    return _collectView;
}

- (void)setHiddenDraggingScroll:(BOOL)hiddenDraggingScroll {
    _hiddenDraggingScroll = hiddenDraggingScroll;
    if (hiddenDraggingScroll) {
        self.collectView.scrollEnabled = NO;
    }else {
        self.collectView.scrollEnabled = NO;
    }
}

#pragma mark ---瀑布流代理方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([self.delegate numberOfItemsForCarouselView:self] == 0) {
        return 0;
    }
    return 3;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    int index = (int)self.currentIndex%[self.delegate numberOfItemsForCarouselView:self];
    if ([self.delegate respondsToSelector:@selector(carouselView:scrollToIndex:)]) {
        [self.delegate carouselView:self scrollToIndex:index];
    }
    if (indexPath.row == 0) {
        index = (int)(self.currentIndex + [self.delegate numberOfItemsForCarouselView:self] -1) % [self.delegate numberOfItemsForCarouselView:self];
    }else if(indexPath.row == 2) {
        index = (int)(self.currentIndex + [self.delegate numberOfItemsForCarouselView:self] + 1) % [self.delegate numberOfItemsForCarouselView:self];
    }
    UICollectionViewCell * cell = [self.delegate carouselView:self cellForItemAtIndex:index];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(collectionView.frame.size.width, collectionView.frame.size.height);
}

-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    int index = (int)self.currentIndex;
    if (indexPath.row == 0) {
        index = (int)(self.currentIndex + [self.delegate numberOfItemsForCarouselView:self] -1) % [self.delegate numberOfItemsForCarouselView:self];
    }else if(indexPath.row == 2) {
        index = (int)(self.currentIndex + [self.delegate numberOfItemsForCarouselView:self] + 1) % [self.delegate numberOfItemsForCarouselView:self];
    }
    if ([self.delegate respondsToSelector:@selector(carouselView:didSelectedAtIndex:)]) {
        [self.delegate carouselView:self didSelectedAtIndex:index];
    }
}

- (void)registerClass:(nullable Class)cellClass forCellWithReuseIdentifier:(NSString *)identifier {
    [self.collectView registerClass:cellClass forCellWithReuseIdentifier:identifier];
}

- (__kindof UICollectionViewCell *)dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndex:(NSInteger)index {
    int rowNumber = 1;
    if (index < self.currentIndex) {
        rowNumber = 0;
    }else if (index > self.currentIndex) {
        rowNumber = 2;
    }
    UICollectionViewCell * cell = [self.collectView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:[NSIndexPath indexPathForRow:rowNumber inSection:0]];
    return cell;
}

#pragma mark --- 滑动代理
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    int page = self.collectView.contentOffset.x / (self.collectView.frame.size.width - 1);
    if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
        page = self.collectView.contentOffset.y / (self.collectView.frame.size.height - 1);
    }
    if ([self.delegate numberOfItemsForCarouselView:self] == 0) {
        [self reloadData];
        return;
    }
    if (page == 0) {
        self.currentIndex = (self.currentIndex + [self.delegate numberOfItemsForCarouselView:self] - 1) % [self.delegate numberOfItemsForCarouselView:self];
    }else if(page == 2){
        self.currentIndex = (self.currentIndex + 1) % [self.delegate numberOfItemsForCarouselView:self];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    int page = self.collectView.contentOffset.x / (self.collectView.frame.size.width - 1);
    if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
        page = self.collectView.contentOffset.y / (self.collectView.frame.size.height - 1);
    }
    if ([self.delegate numberOfItemsForCarouselView:self] == 0) {
        [self reloadData];
        return;
    }
    if (page == 0) {
        self.currentIndex = (self.currentIndex + [self.delegate numberOfItemsForCarouselView:self] - 1) % [self.delegate numberOfItemsForCarouselView:self];
    }else if(page == 2){
        self.currentIndex = (self.currentIndex + 1) % [self.delegate numberOfItemsForCarouselView:self];
    }
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (_timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
     [self setUpTimer];
}

- (void)reloadData {
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.collectView reloadData];
        [weakSelf.collectView layoutIfNeeded];
        if (self.scrollDirection == UICollectionViewScrollDirectionVertical) {
            [weakSelf.collectView setContentOffset:CGPointMake(0, weakSelf.collectView.frame.size.height) animated:NO];
        }else {
            [weakSelf.collectView setContentOffset:CGPointMake(weakSelf.collectView.frame.size.width, 0) animated:NO];
        }
        
        if ([weakSelf.delegate numberOfItemsForCarouselView:weakSelf] > 1) {
            weakSelf.pageControl.numberOfPages = [weakSelf.delegate numberOfItemsForCarouselView:weakSelf];
            weakSelf.pageControl.currentPage = weakSelf.currentIndex;
            weakSelf.pageControl.hidden = NO;
            if (weakSelf.hiddenDraggingScroll == NO) {
                weakSelf.collectView.scrollEnabled = YES;
            }
            
        }else {
            weakSelf.pageControl.hidden = YES;
            weakSelf.collectView.scrollEnabled = NO;
        }
        [weakSelf setUpTimer];
    });
    
}

- (void)setCurrentIndex:(NSUInteger)currentIndex {
    if ([self.delegate numberOfItemsForCarouselView:self] <= 0) {
        [self reloadData];
        return;
    }
    _currentIndex = currentIndex%[self.delegate numberOfItemsForCarouselView:self];
    [self reloadData];
}

@end


